package org.ycsoft.PathComputation;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.zip.Deflater;

/**
 * Wrapper class for all common constants and methode
 * @author allad
 *
 */
public class Commons {
	
	
	public static final int INFINITY = Integer.MAX_VALUE; //Positive Infinity constant
	public static final int DEFAULT_EDGE_LENGTH = 5*60; //Default travel time for an edge in seconds
	public static final Stop STOP_NULL = new Stop(null); //Null stop
	public static final Line LINE_NULL = new Line(null,-1,-1); //Null Line
	public static final char LINE_SEPARATOR = '\n';
	public static final String DEFAULT_ENCODING = "utf-8";
	public static final int ID_DIGITS_NB = 4; //number of digits to format ids to
	public static final int POSITION_DIGITS_NB = 7; //number of digits to format file positions to
	public static final int LENGTH_DIGITS_NB = 5; //number of digits to travel lengths to
	public static final String METROID_EXTENSION = "mtd";
	public static final char PREFIX = '.';
	public static final char SEPARATOR = ':';
	public static final String UNIDIRECTIONAL = PREFIX+"unidirectional";
	
	
	/**
	 * Format a number to a string reprensatation
	 * @param n Number
	 * @param nbDigits Number of digits to write (leading zeros are added)
	 * @return
	 */
	public static String formatNumber(long n,int nbDigits){
		String tmp = String.valueOf(nbDigits);
		return String.format("%1$0"+tmp+"d", n);
	}


	
	/**
	 * Compress the input string using the Deflate algorithm
	 * @param data
	 * @return The compressed stream of bytes
	 */
	public static byte[] compressString(String data){
		if(data == null)
			return null;
		byte[] tmp;
		try {
			tmp = data.getBytes(DEFAULT_ENCODING);
		}catch(UnsupportedEncodingException e){
			tmp = data.getBytes();
		}
		
		// Compress the bytes
	     byte[] output = new byte[tmp.length];
	     Deflater compresser = new Deflater();
	     compresser.setLevel(Deflater.BEST_SPEED);
	     compresser.setInput(tmp);
	     compresser.finish();
	  // Create an expandable byte array to hold the compressed data.
	     // You cannot use an array that's the same size as the orginal because
	     // there is no guarantee that the compressed data will be smaller than
	     // the uncompressed data.
	     ByteArrayOutputStream bos = new ByteArrayOutputStream(tmp.length);
	     
	     // Compress the data
	     byte[] buf = new byte[1024];
	     while (!compresser.finished()) {
	         int count = compresser.deflate(buf);
	         bos.write(buf, 0, count);
	     }
	     try {
	         bos.close();
	     } catch (IOException e) {
	     }
	     
	     // Get the compressed data
	     byte[] compressedData = bos.toByteArray();
	    return compressedData;
	}

	
}
